import { HashMap } from '../utils/hashmap'
import $ from 'jquery'
import 'jquery-ui-dist/jquery-ui'
import 'jquery-ui-dist/jquery-ui.css'
import '../utils/jquery.contextmenu.r2'
import { requestOpts } from '@/utils/request.js'
import { fontItemArray } from '@/const/index.js'

const clock_img = require('@/assets/clock.png')
export const TemplateOptions = {
    methods: {
        layoutInit() {
            this.widgetData = new HashMap();
            this.widgetData.clear();
            $('#compont').html('');
            $('#accordion').find('a').each(function () {
                $(this).removeClass('notclick');
                $(this).addClass('addWiget');
            });
            if (this.twidget === undefined || this.twidget == null || this.twidget.length < 1) {
                return;
            }
            var coindex = 0;
            let _this = this;
            $.each(this.twidget,function(i) {
                coindex++;
                var type = _this.twidget[i]['type'];
                var keyid = type + _this.twidget[i]['index'];
                _this.widgetData.put(keyid, _this.twidget[i]);
                _this.addWiget(_this.twidget[i], type);
            });
            $('#accordion').find('a').attr('index',coindex);
            setTimeout(() => {
                $.each(this.twidget,function(i) {
                    var type = _this.twidget[i]['type'];
                    var keyid = type + _this.twidget[i]['index'];
                    setTimeout(() => {
                        _this.doUpdateAttrForm(keyid)
                    }, 100)
                })
            }, 100);
        },
        // 修改模板类型
        async doChangeResolution(resolution) {
            let _this = this;
            let len = this.widgetData.size()
            let res = true
            if(len > 0) {
                res = await this.$confirm('提示', '更换分辨率会清空区域，确认要更换吗？')
            }
            if (res) {
                _this.parseResolution(resolution);
                _this.widgetData.clear();
                _this.twidget = []
                _this.resetVal();
                $('#compont').html('');
                $('#accordion').find('a').each(function () {
                    $(this).removeClass('notclick');
                    $(this).addClass('addWiget');
                });
                return true
            }
            return false
        },
        // 更新属性值
        doUpdateAttrForm(key) {
            $('#right').attr('currentSelectedWidgetId',key);
            const itemData = this.widgetData.get(key)
            const x = itemData['x']
            const y = itemData['y']
            const w = itemData['w']
            const h = itemData['h']
            const avl = itemData['avl']
            const zindex = itemData['zindex']
            const type = itemData.type
            this.$nextTick(() => {
                this.attrForm.formData.name = itemData['title']
                this.attrForm.formData.title = itemData.name
                this.attrForm.showArea = type
                this.attrForm.formData.X = x
                this.attrForm.formData.Y = y
                this.attrForm.formData.W = w
                this.attrForm.formData.H = h
                this.attrForm.formData.Z = zindex
                this.attrForm.formData.showType = type
                if (type === 'Clock') {
                    const model = this.attrForm.formData.clockModel
                    if(model === 'Digital') {
                        const clockPrams = {}
                        clockPrams.html = this.$changeTemplateClockFormat(this.attrForm.formData.clockTimeFormat)
                        clockPrams.size = this.attrForm.formData.clockFontsize
                        clockPrams.color = this.attrForm.formData.clockFontColor
                        clockPrams.font = this.attrForm.formData.clockFont
                        clockPrams.mode = model
                        clockPrams.format = this.attrForm.formData.clockTimeFormat
                        clockPrams.align = 'left'
                        // 添加属性
                        this.updateSelectedWidget(clockPrams, 9)
                    }
                }else if(type === 'Background') {
                    const bgimg = itemData['bgimg']
                    if(bgimg) {
                        this.attrForm.formData.bgfile = bgimg
                        this.updateSelectedWidget(bgimg, 2)
                    }else {
                        this.attrForm.formData.bgfile = ''
                    }
                }else if(type === 'Weather') {
                    const tableData = []
                    const weatherAttr = itemData['weatherAttr']
                    if(weatherAttr) {
                        const img = ((requestOpts.noseUrl).endsWith('/') ? requestOpts.noseUrl : requestOpts.noseUrl  + '/') + 'v1/weather?cityId=' + this.attrForm.formData.city +'&corpCode=' + requestOpts.corpCode + '&provinceId=' + this.attrForm.formData.province + '&style=' + this.attrForm.formData.weatherStyle
                        this.updateSelectedWidget(img, 7)
                        weatherAttr.forEach(item => {
                            tableData.push({
                                index: item.index,
                                province: item.province,
                                city: item.city,
                                provinceName: item.provinceName,
                                cityName: item.cityName,
                                switchTime: item.switchTime,
                                url: item.url ? item.url : '',
                                style: item.style
                            })
                        })
                        this.attrForm.formData.weatherAttr = tableData
                        this.updateSelectedWidget(tableData, 8)
                    }
                }else if(type === 'Timer') {
                    const clockPrams = {}
                    clockPrams.html = this.$changeTemplateTimerFormat(
                        this.attrForm.formData.timerType, 
                        this.attrForm.formData.link,
                        this.attrForm.formData.timerEndDate + ' ' + this.attrForm.formData.timerEndTime
                    )
                    clockPrams.type = this.attrForm.formData.timerType
                    clockPrams.mode = this.attrForm.formData.link
                    clockPrams.font = this.attrForm.formData.timerFont
                    clockPrams.size = this.attrForm.formData.timerFontsize
                    clockPrams.color = this.attrForm.formData.timerFontColor
                    clockPrams.endDate = this.attrForm.formData.timerEndDate
                    clockPrams.endTime = this.attrForm.formData.timerEndTime
                    clockPrams.align = 'left'
                    // 添加属性
                    this.updateSelectedWidget(clockPrams, 10)
                }else if(type === 'Main') {
                    itemData['avl'] = avl
                    this.attrForm.formData.anchorAvl = avl ? avl : 0
                }else if(type === 'Mixed') {
                    itemData['avl'] = avl
                    this.attrForm.formData.videoAvl = avl ? avl : 0
                }else if(type === 'Audio') {
                    itemData['avl'] = avl
                    this.attrForm.formData.audioAvl = avl ? avl : 0
                }
            })
        },
        parseResolution(resolution) {
            this.templateOpts = {
                width: Number(resolution.split('*')[0]),
                height: Number(resolution.split('*')[1].match(/[0-9]*/)[0])
            }
        },
        widgetUpdate(view, itemData) {
            const x = Number(itemData['x'])
            const y = Number(itemData['y'])
            const w = Number(itemData['w'])
            const h = Number(itemData['h'])

            view.css('top', `${y * this.iheightPercent}px`)
            view.css('left', `${x * this.iwidthPercent}px`)
            view.css('width', `${w * this.iwidthPercent}px`)
            view.css('height', `${h * this.iheightPercent}px`)
        },
        widgetResize(view,left,top,width,height,drag) {
            var keyId = view.attr('id');
            if ((left + width) > this.wrapperWidth) {
                width = this.wrapperWidth - left;
            }
            if ((top + height) > this.wrapperHeight) {
                height = this.wrapperHeight - top;
            }
            if (drag) {
                let x = Math.round(left / this.iwidthPercent);
                let y = Math.round(top / this.iheightPercent);
                let w = this.widgetData.get(keyId)['w'];
                let h = this.widgetData.get(keyId)['h'];
                if(( x + w) > Number(this.templateOpts.width)) {
                    x = Number(this.templateOpts.width) - w
                }
                if(( y + h) > Number(this.templateOpts.height)) {
                    y = Number(this.templateOpts.height) - h
                }
                // 更新xy坐标值
                this.$nextTick(() => {
                    this.attrForm.formData.X = x
                    this.attrForm.formData.Y = y
                    if (this.widgetData.containsKey(keyId)) {
                        this.widgetData.get(keyId)['x'] = x;
                        this.widgetData.get(keyId)['y'] = y;
                    }
                })
                
            } else {
                let w = Math.round(width / this.iwidthPercent);
                let h = Math.round(height / this.iheightPercent);
                if(w > Number(this.templateOpts.width)) {
                    w = this.templateOpts.width
                }
                if(h > Number(this.templateOpts.height)) {
                    h = this.templateOpts.height
                }
                this.$nextTick(() => {
                     // 更新wh高宽度
                    this.attrForm.formData.W = w
                    this.attrForm.formData.H = h
                    if (this.widgetData.containsKey(keyId)) {
                        this.widgetData.get(keyId)['w'] = w;
                        this.widgetData.get(keyId)['h'] = h;
                    }
                })
               
            }
        },
        widgetSelected($this) {
            var key = $this.attr('id');
            var type = $this.attr('type');
            // $('#right').attr('currentSelectedWidgetId',key);
            // $('#index').html(Number($this.attr('xindex')));
            this.updateSelectedWidgetParams(key, type, $this.attr('name'))
        },
        // 获取widget相关信息
        __getWidgetInfo(widget) {
            return {
                x: this.__px2real(widget.css('left')),
                y: this.__px2real(widget.css('top')),
                width: this.__px2real(widget.css('width')),
                height: this.__px2real(widget.css('height')),
                name: widget.attr('name'),
                z: widget.css('z-index')
            }
        },
        // px 2 number
        __px2number(px) {
            return Number(px.replace('px', ''))
        },
        // px 2 real 元素px值转实际模版值
        __px2real(px) {
            return Math.round(this.__px2number(px) / this.iwidthPercent)
        },
        // 给widget设置素材
        __widgetSetElement(widget, elementOpts) {
            const eleStyle = 'width: 100%; height: 100%; position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px;'
            switch(elementOpts.type) {
                case 'video':
                    widget.html(`<video autoplay src="${elementOpts.url}" style="${eleStyle}" />`)
                    break;
                case 'img':
                    widget.html(`<img src="${elementOpts.url}" style="${eleStyle}" />`)
                    break;
                default:
            }
        },
        // 刷新属性参数
        updateSelectedWidgetParams(key,type,name) {
            $('#areaName').attr('widgetId',key);
            $('#areaName').val(name);
            if (this.widgetData.containsKey(key)) {
                this.doUpdateAttrForm(key)
            } else {
                this.resetVal()
            }
        },
        updateSelectedWidget(val, flag) {
            const currentSelectedWidgetId = $('#right').attr('currentSelectedWidgetId');
            let _this = this;
            $('#compont').children().each(function() {
                const id = $(this).attr('id');
                const itemData = _this.widgetData.get(id);
                    if (itemData != null && id === currentSelectedWidgetId) {
                        const isValid = _this.isModifyValid(val, flag, itemData);
                        if (!isValid) {
                            _this.$alert('提示', '已经超出分辨率')
                            return;
                        }
                        switch (flag) {
                            // 改z轴
                            case 1:
                                $(this).css("z-index", val);
                                itemData['zindex'] = Number(val)
                                break
                            // 改背景
                            case 2:
                                $(this).css({ 'background': 'url('+val+')', 'background-size': '100% 100%' })
                                itemData['bgimg'] = val
                                break
                            // 改X坐标
                            case 3:
                                $(this).css("left", `${val * _this.iwidthPercent}px`);
                                itemData['x'] = Number(val)
                                break
                            // 改Y坐标
                            case 4:
                                $(this).css('top', `${val * _this.iheightPercent}px`)
                                itemData['y'] = Number(val)
                                break
                            // 改宽度
                            case 5:
                                $(this).css('width', `${val * _this.iwidthPercent}px`)
                                itemData['w'] = Number(val)
                                break
                            // 改高度
                            case 6:
                                $(this).css('height', `${val * _this.iheightPercent}px`)
                                itemData['h'] = Number(val)
                                break
                            // 改天气
                            case 7:
                                $(this).find('img').attr('src', val)
                                break
                            // 改天气属性
                            case 8:
                                itemData['weatherAttr'] = val
                                break
                            // 改时钟属性
                            case 9:
                                itemData['clockAttr'] = val
                                $(this).find('span').html(val.html)
                                $(this).find('span').css({'font-size':  Math.round(val.size/4), 'color': val.color, 'font-family': fontItemArray[val.font === 0 ? 25  : val.font].name, 'generic-family': 'Georgia,Serif'})
                                break
                            // 改计时属性
                            case 10:
                                itemData['timerAttr'] = val
                                $(this).find('span').html(val.html)
                                $(this).find('span').css({'font-size':  Math.round(val.size/4), 'color': val.color, 'font-family': fontItemArray[val.font === 0 ? 25  : val.font].name, 'generic-family': 'Georgia,Serif'})
                                break
                            case 11:
                                if(val === 'Digital') {
                                    $(this).find('span').html('00:00')
                                }else if(val === 'analog') {
                                    $(this).find('span').html('<img src='+clock_img+' style="width:100%;height:100%;position:absolute;top:0; left:0;right: 0; bottom: 0;"></img>')
                                }
                                break
                            case 12:
                                itemData['title'] = val
                                break
                            case 13:
                                itemData['avl'] = val
                                break
                        }
                    }
                // }
            });
        },
        isModifyValid(srx,flag,itemData) {
            var retVal = true;
            var iW = 0;
            var iH = 0;
            var iX = 0;
            var iY = 0;
            var tmpX = 0;
            var tmpY = 0;
            switch (flag) {
                case 3:
                    iX = Number(this.attrForm.formData.W) + Number(srx);
                    if (iX > this.templateOpts.width) {
                        // this.attrForm.formData.W = itemData['w']
                        retVal = false;
                    }
                    break;
                case 4:
                    iY = Number(this.attrForm.formData.H) + Number(srx);
                    if (iY > this.templateOpts.height) {
                        // this.attrForm.formData.H = itemData['h']=
                        retVal = false;
                    }
                    break;
                case 5:
                    iW = Number(this.attrForm.formData.X) + Number(srx);
                    if (iW > this.templateOpts.width) {
                        // this.attrForm.formData.X = itemData['x']
                        retVal = false;
                    }
                    break;
                case 6:
                    iH = Number(this.attrForm.formData.Y) + Number(srx);
                    if (iH > this.templateOpts.height) {
                        // this.attrForm.formData.Y = itemData['y']
                        retVal = false;
                    }
                    break;
            }
            return retVal;
        },
        addWiget(itemData, type) {
            var divAdd;
            var keyId = type + itemData['index'];
            let widget
            if (type === 'ImageText' || type === 'Mixed' || type === 'Web') {
            } else {
                widget = $('#accordion').find('a[name=' + type + ']');
                widget.removeClass('addWiget');
                widget.addClass('notclick');
                var widExist = $('#compont').find('[id=' + keyId + ']');
                if (widExist.length > 0) {
                    return;
                }
            }
            switch (type) {
                case 'Background':
                    divAdd = $('#backgroundC').clone();
                    divAdd.text('');
                    break;
                // 主播区
                case 'Main':
                    divAdd = $('#anchorC').clone();
                    break;
                // 综合区
                case 'Mixed':
                    divAdd = $('#videoC').clone();
                    break;
                // 音频区
                case 'Audio':
                    divAdd = $('#liveC').clone();
                    break;
                // 图文区
                case 'ImageText':
                    divAdd = $('#imageC').clone();
                    break;
                // 时钟区
                case 'Clock':
                    divAdd = $('#dateC').clone();
                    break;
                // 计时区
                case 'Timer':
                    divAdd = $('#timeC').clone();
                    break;
                // 天气区
                case 'Weather':
                    divAdd = $('#weatherC').clone();
                    break;
                // 网页区
                case 'Web':
                    divAdd = $('#webC').clone();
                    break;
                // 扩展区
                case 'Extension': 
                    divAdd = $('#formC').clone();
                    break;
                //滚动条
                case 'Scroll':
                    divAdd = $('#scollC').clone();
                    break;
            }
            divAdd.css('display','block').css('position','absolute').attr('xindex',itemData['index']).attr('name',itemData['name']).attr('id',keyId).attr('type',type);
            this.widgetUpdate(divAdd,itemData);
            let _this = this;
            // 背景不允许拖动
            if(type !== 'Background') {
                divAdd.draggable({
                    containment: '#compont',
                    scroll: false,
                    // stack: '#compont div',
                    opacity: 0.5,
                    drag: function(event, ui) {
                        _this.widgetResize(divAdd,ui.position.left,ui.position.top,divAdd.width(),divAdd.height(),true);
                    },
                    start: function(event, ui) {
                        _this.widgetSelected(divAdd);
                    },
                    stop: function(event, ui) {
                    }
                });
                divAdd.resizable({
                    containment: '#compont',
                    start: function(event, ui) {
                        _this.widgetSelected(divAdd);
                    },
                    resize: function(event, ui) {
                        _this.widgetResize(divAdd,divAdd.position().left,divAdd.position().top,ui.size.width,ui.size.height,false);
                    }
                });
            }
            divAdd.click(function () {
                _this.widgetSelected($(this));
            });
            divAdd.css('z-index', itemData['zindex']);
            $('#compont').append(divAdd);
            // 模板被使用,不允许删除
            if(this.attrForm.formData.refCount === 0 || !this.attrForm.formData.refCount) {
                this.bindMenu(divAdd,type);
            }
            // 个数判断
            const name =  itemData['name']
            const exist = $('#compont').find('[name=' + name + ']');
            if(type === 'Web' && exist.length > 1) {
                widget = $('#accordion').find('a[name=' + type + ']');
                widget.removeClass('addWiget');
                widget.addClass('notclick');
                return
            } else if(type === 'Mixed' && exist.length > 2) {
                widget = $('#accordion').find('a[name=' + type + ']');
                widget.removeClass('addWiget');
                widget.addClass('notclick');
                return
            } else if(type === 'ImageText' && exist.length > 4) {
                widget = $('#accordion').find('a[name=' + type + ']');
                widget.removeClass('addWiget');
                widget.addClass('notclick');
                return
            }
        },
        bindMenu(divAdd, type) {
            let _this = this;
            divAdd.contextMenu('myMenu', {
                menuStyle: {
                    border: '0'
                },
                bindings: {
                    'item_1': function(t) {
                        $('#' + t.id).remove();
                        _this.removeWidget(t.id, type);
                    }
                }
            });
        },
        removeWidget(id,type) {
            this.resetVal();
            var deleteId = this.widgetData.get(id)['id'];
            if (deleteId !== undefined && deleteId != null && deleteId !== '') {
                this.discardIds += deleteId + ',';
            }
            this.widgetData.remove(id);
            var a = $('#accordion').find('a[name=' + type + ']');
            a.removeClass('notclick');
            a.addClass('addWiget');
            if(type === 'Background') {
                this.attrForm.formData.mediaId = 0
            }
        },
        resetVal() {
            this.attrForm.formData.title = ''
            this.attrForm.showArea = 'main'
            this.attrForm.formData.X = 0
            this.attrForm.formData.Y = 0
            this.attrForm.formData.W = 0
            this.attrForm.formData.H = 0
        },
        initNeedAddWidgetInfo(name, avl) {
            // 清空属性值
            this.resetVal();

            const $this = $("[name='" + name + "']");
            var type = $this.attr('name');
            var index = $this.attr('index');
            var key = type + index;
            var itemData = {};
            var addWidth = 200;
            var addHeight = 200;
            switch (type) {
                case 'Background':
                    addWidth = this.templateOpts.width * this.iwidthPercent;
                    addHeight = this.templateOpts.height * this.iheightPercent;
                    break;
                case 'Main':
                    addWidth = 400;
                    addHeight = 400;
                    break;
                case 'Mixed':
                    addWidth = 400;
                    addHeight = 400;
                    break;
                case 'Audio':
                    addWidth = 400;
                    addHeight = 400;
                    break;
                case 'ImageText':
                    addWidth = 400;
                    addHeight = 400;
                    break;
                case 'Clock':
                    addWidth = 400;
                    addHeight = 150;
                    break;
                case 'Timer':
                    addWidth = 400;
                    addHeight = 150;
                    break;
                case 'Weather':
                    addWidth = 400;
                    addHeight = 280;
                    break;
                case 'Web':
                    addWidth = 400;
                    addHeight = 400;
                    break;
                case 'Mask':
                    addWidth = 400;
                    addHeight = 400;
                    break;
                case 'Extension':
                    addWidth = 400;
                    addHeight = 400;
                    break;
                case 'Scroll':
                    addWidth = 400;
                    addHeight = 300;
                    break;
                default:break;
            }
            if(type === 'Background') {
                itemData['w'] = Math.round(addWidth / this.iwidthPercent);
                itemData['h'] = Math.round(addHeight / this.iheightPercent);
                itemData['zindex'] = 0;
            } else {
                itemData['w'] = addWidth
                itemData['h'] = addHeight
                itemData['zindex'] = this.getMaxZindex() + 1;
            }
            itemData['x'] = '0';
            itemData['y'] = '0';
            itemData['name'] = $this.text();
            itemData['type'] = type;
            // itemData['zindex'] = this.getMaxZindex() + 1;
            itemData['index'] = index;
            itemData['title'] = key
            if(type === 'Main' || type === 'Mixed' || type === 'Audio'){
                itemData['avl'] = avl
            }
            $this.attr('index', Number(index) + 1);
            this.widgetData.put(key, itemData);
            this.addWiget(itemData, type);
            this.doUpdateAttrForm(key);
        },
        getMaxZindex() {
            var max = 0;
            $('#compont').children().each(function () {
                var zindex = Number($(this).css('z-index'));
                max = max > zindex ? max : zindex;
            });
            return max;
        },
        originalTemplateSize(width, height, isReduction) {
            const view = $('#compont')
            view.css('width', `${width}px`)
            view.css('height', `${height}px`)
            this.widgetData.values().forEach(item => {
                const index = item.index
                const type = item.type
                const objid = type + index
               
                let addWidth = item.w
                let addHeight = item.h
                let top = 0
                let left = 0
                if(!isReduction) {
                    addWidth = addWidth * this.iwidthPercent
                    addHeight = addHeight * this.iwidthPercent
                    top = item.y * this.iheightPercent
                    left = item.x * this.iwidthPercent
                } else {
                    top = item.y
                    left = item.x
                }
                $('#' + objid)
                .css('width', `${addWidth}px`)
                .css('height', `${addHeight}px`)
                .css("top", `${top}px`)
                .css("left", `${left}px`)
            })
        }
    }
}